import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_baselib/flutter_baselib.dart';
import 'package:flutter_nativedialog_plugin/loadingdialog_plugin.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:baselib_demo/common/config/app_config.dart';
import 'package:baselib_demo/common/config/res_config_impl.dart';
import 'package:baselib_demo/common/config/third_params_config.dart';
import 'package:baselib_demo/common/config/toast_impl.dart';
import 'package:baselib_demo/common/net/config/http_config_impl.dart';
import 'package:baselib_demo/common/router/routes.dart';
import 'package:baselib_demo/common/util/env/dev_env_utils.dart';
import 'package:baselib_demo/common/util/env/env_config_plugin.dart';

///@date:  2021/4/20 15:20
///@author:  lixu
///@description: 依赖的三方库管理工具
class SdkManager {
  SdkManager._();

  ///应用全局日志tag
  static const _appTag = 'TGameApp';
  static const _tag = 'SdkManager';

  ///初始化三方库
  static Future<void> init(BuildContext context) async {
    ///初始化fluro路由库(要放在最开始初始化)
    Routes.initRouters();

    ///初始化公共库
    await _initBaseLib(context);

    ///加载框样式设置
    LoadingDialogPlugin.defStyle = LoadingStyle.ThreeBounce;
  }

  ///初始化基础库
  static Future _initBaseLib(BuildContext context) async {
    LogUtils.i(_tag, 'initBaseLib start');

    await BaseLibPlugin.init(
      isDebug: await _isDebug(),
      //全局通用资源配置
      resConfig: ResConfigImpl(),
      //toast相关配置
      toastImpl: ToastImpl(),
      //bugly相关配置
      buglyConfig: BuglyConfig.defaultAndroid(ThirdParamsConfig.buglyAppId),
      //日志库配置
      logConfig: LogConfig.obtain(
        tag: _appTag,
        isConsolePrintLog: await isConsolePrintLog(),
        isFlutterPrintLog: false,
        //保存到外部路径时，需要获取存储权限，可以先设置路径，后获取权限,xlog内部会自动处理
        saveLogFilePath: await _getLogDir(),
        encryptPubKey: null,
      ),
      //http配置
      httpConfig: HttpConfigImpl(),
    );

    LogUtils.i(_tag, 'initBaseLib finish');
  }

  ///控制台是否打印日志
  static Future<bool> isConsolePrintLog() {
    return EnvConfigPlugin.isConsoleLog();
  }

  ///是否是debug模式，满足下面一个条件就认定是debug
  ///1、调试运行
  ///2、使用的测试服
  static Future<bool> _isDebug() async {
    return DevEnvUtils.isDebug() || await DevEnvUtils.isShowSwitchServerEnvUI();
  }

  ///获取log存储路径
  static Future<String> _getLogDir() async {
    Directory? dir = await PathUtils.getExternalStorageDir();
    if (dir == null) {
      return AppConfig.defaultLogCacheDir;
    } else {
      return '${dir.path}${AppConfig.logCacheDir}';
    }
  }

  ///初始化屏幕适配工具：方式一（初始化方法，使用其中一个即可）
  ///初始化并设置适配尺寸及字体大小是否根据系统的“字体大小”辅助选项来进行缩放
  ///https://github.com/OpenFlutter/flutter_screenutil/blob/master/README_CN.md
  static Widget initScreenUtil(Widget Function() builder) {
    return ScreenUtilInit(
      designSize: Size(360, 690),
      builder: builder,
    );
  }

  ///初始化屏幕适配工具：方式二
  ///不支持在MaterialApp的theme的textTheme中使用字体适配
  static void initScreenUtil2(BuildContext context) {
    ///设置尺寸（填写设计中设备的屏幕尺寸）如果设计基于360dp * 690dp的屏幕
    ScreenUtil.init(
      BoxConstraints(
        maxWidth: MediaQuery.of(context).size.width,
        maxHeight: MediaQuery.of(context).size.height,
      ),
      designSize: Size(360, 690),
      orientation: Orientation.portrait,
    );
  }

  ///应用关闭时调用
  static Future? dispose() async {
    return BaseLibPlugin.dispose();
  }
}
